<template>
	<s-layout title="闲置商品发布">
		<uni-forms ref="addressFormRef" v-model="state.model" :rules="rules" validateTrigger="bind" labelWidth="160"
			labelAlign="left" border :labelStyle="{ fontWeight: 'bold' }">
			<view class="bg-white form-box ss-p-x-30">
				<uni-forms-item name="productName" label="商品名称" class="form-item">
					<uni-easyinput v-model="state.model.productName" placeholder="请填写商品名称" :inputBorder="false"
						placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal" />
				</uni-forms-item>
				<uni-forms-item name="productLabel" label="商品分类" class="form-item">
					<picker @change="bankChange" :value="state.model.productLabel" :range="productLabel"
						style="width: 100%" range-key="label">
						<uni-easyinput type="digit" v-model="state.model.productLabel" placeholder="请选择商品分类"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal" />
					</picker>
				</uni-forms-item>
				<uni-forms-item name="productPrice" label="商品价格" class="form-item">
					<uni-easyinput type="digit" v-model="state.model.productPrice" placeholder="请填写商品价格" :inputBorder="false"
						placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal" />
				</uni-forms-item>
				<uni-forms-item name="images" label="商品图片" class="form-item">
					<s-uploader v-model:url="state.model.images" fileMediatype="image" limit="9" mode="grid"
						:imageStyles="{ width: '168rpx', height: '168rpx' }" />
				</uni-forms-item>
				<uni-forms-item name="videos" label="商品视频" class="form-item">
					<s-uploader v-model:url="state.model.videos" fileMediatype="video" limit="2" mode="grid"
						:imageStyles="{ width: '168rpx', height: '168rpx' }" />
				</uni-forms-item>

				<uni-forms-item name="detailAddress" label="其他介绍" :formItemStyle="{ alignItems: 'flex-start' }"
					:labelStyle="{ lineHeight: '5em' }" class="textarea-item">
					<uni-easyinput :inputBorder="false" type="textarea" v-model="state.model.detailAddress"
						placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
						placeholder="请输入详细介绍" clearable />
				</uni-forms-item>
			</view>
		</uni-forms>
		<su-fixed bottom :opacity="false" bg="" placeholder :noFixed="false" :index="10">
			<view class="footer-box ss-flex-col ss-row-between ss-p-20">
				<view class="ss-m-b-20">
					<button class="ss-reset-button save-btn ui-Shadow-Main" @tap="onSave">保存</button>
				</view>
				<button v-if="state.model.id" class="ss-reset-button cancel-btn" @tap="onDelete">
					删除
				</button>
			</view>
		</su-fixed>

		<!-- 省市区弹窗 -->
		<su-region-picker :show="state.showRegion" @cancel="state.showRegion = false" @confirm="onRegionConfirm" />
	</s-layout>
</template>

<script setup>
	import {
		ref,
		reactive,
		unref
	} from 'vue';
	import sheep from '@/sheep';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import _ from 'lodash-es';
	import FileApi from '@/sheep/api/infra/file';
	import {
		mobile
	} from '@/sheep/validate/form';
	import AreaApi from '@/sheep/api/system/area';
	import AddressApi from '@/sheep/api/member/address';
	import SecondProductApi from '@/sheep/api/second/product.js';
	const addressFormRef = ref(null);
	const state = reactive({
		showRegion: false,
		model: {
			productName: '',
			productPrice:'',
			images:[],
			videos:[]
		},
		rules: {},
	});

	const productLabel = ref([{
		label: "电子产品",
		id: 1
	}, {
		label: "家具家居",
		id: 2
	}, {
		label: "服装服饰",
		id: 3
	}, {
		label: "母婴用品",
		id: 4
	}, {
		label: "运动户外",
		id: 5
	}, {
		label: "其他",
		id: 6
	}])

	const rules = {
		productName: {
			rules: [{
				required: true,
				errorMessage: '请输入商品名称',
			}, ],
		},
		productPrice: {
			rules: [{
				required: true,
				errorMessage: '请输入商品价格',
			}, ],
		},
		productLabel: {
			rules: [{
				required: true,
				errorMessage: '请选择商品标签',
			}, ],
		}
	};

	// 确认选择地区
	const onRegionConfirm = (e) => {
		state.model.areaName = `${e.province_name} ${e.city_name} ${e.district_name}`;
		state.model.areaId = e.district_id;
		state.showRegion = false;
	};

	// 获得地区数据
	const getAreaData = () => {
		if (_.isEmpty(uni.getStorageSync('areaData'))) {
			AreaApi.getAreaTree().then((res) => {
				if (res.code === 0) {
					uni.setStorageSync('areaData', res.data);
				}
			});
		}
	};

	// 发布闲置商品
	const onSave = async () => {
		// 参数校验
		const validate = await unref(addressFormRef)
			.validate()
			.catch((error) => {
				console.log('error: ', error);
			});
		if (!validate) {
			return;
		}

		// 提交请求
		const formData = {
			...state.model,
			productImages:state.model.images.length?state.model.images.join(','):null,
			productVideos:state.model.videos.length?state.model.videos.join(','):null
		};
		const {
			code
		} =
		state.model.id > 0 ?
			await SecondProductApi.updateAddress(formData) :
			await SecondProductApi.pushSecondProduct(formData);
		if (code === 0) {
			sheep.$router.back();
		}
	};

	const bankChange = (e, v) => {
		const item = productLabel.value[e.detail.value]
		if (item) {
			state.model.productLabel = item.label
		}
	}

	// 删除收货地址
	const onDelete = () => {
		uni.showModal({
			title: '提示',
			content: '确认删除此收货地址吗？',
			success: async function(res) {
				if (!res.confirm) {
					return;
				}
				const {
					code
				} = await AddressApi.deleteAddress(state.model.id);
				if (code === 0) {
					sheep.$router.back();
				}
			},
		});
	};

	onLoad(async (options) => {
		// 获得地区数据
		getAreaData();
		// 情况一：基于 id 获得收件地址
		if (options.id) {
			let {
				code,
				data
			} = await AddressApi.getAddress(options.id);
			if (code !== 0) {
				return;
			}
			state.model = data;
		}
		// 情况二：微信导入
		if (options.data) {
			let data = JSON.parse(options.data);
			const areaData = uni.getStorageSync('areaData');
			const findAreaByName = (areas, name) => areas.find((item) => item.name === name);

			let provinceObj = findAreaByName(areaData, data.province_name);
			let cityObj = provinceObj ? findAreaByName(provinceObj.children, data.city_name) : undefined;
			let districtObj = cityObj ? findAreaByName(cityObj.children, data.district_name) : undefined;
			let areaId = (districtObj || cityObj || provinceObj).id;

			state.model = {
				...state.model,
				name: data.consignee,
			};
		}
	});
</script>

<style lang="scss" scoped>
	:deep() {
		.uni-forms-item__label .label-text {
			font-size: 28rpx !important;
			color: #333333 !important;
			line-height: normal !important;
		}

		.uni-easyinput__content-input {
			font-size: 28rpx !important;
			color: #333333 !important;
			line-height: normal !important;
			padding-left: 0 !important;
		}

		.uni-easyinput__content-textarea {
			font-size: 28rpx !important;
			color: #333333 !important;
			line-height: normal !important;
			margin-top: 8rpx !important;
		}

		.uni-icons {
			font-size: 40rpx !important;
		}

		.is-textarea-icon {
			margin-top: 22rpx;
		}

		.is-disabled {
			color: #333333;
		}
	}

	.default-box {
		width: 100%;
		box-sizing: border-box;
		height: 100rpx;

		.default-box-title {
			font-size: 28rpx;
			color: #333333;
			line-height: normal;
		}
	}

	.footer-box {
		.save-btn {
			width: 710rpx;
			height: 80rpx;
			border-radius: 40rpx;
			background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
			color: $white;
		}

		.cancel-btn {
			width: 710rpx;
			height: 80rpx;
			border-radius: 40rpx;
			background: var(--ui-BG);
		}
	}
</style>